package com.tian.auto.parse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.tian.auto.Constants;
import com.tian.auto.Log;
import com.tian.auto.StringUtils;
import com.tian.auto.info.ResData;
import com.tian.auto.model.CnUpdateModel;
import com.tian.auto.model.EnUpdateModel;
import com.tian.auto.model.ThrTHUpdateModel;
import com.tian.auto.model.ZhrTWUpdateModel;

import java.util.HashMap;
import java.util.List;

import static com.tian.auto.Constants.ERROR_LOG_LIST;

/**
 * 解析excel中的数据，并更新目标工程对应资源的值
 */
public class ParseExcelCore {

    /**
     * 读取excel表，并更新目标工程对应资源的值
     *
     * @param path
     */
    public void read(String path, boolean isNeedMatchModuleName) {
        ExcelReader excelReader = EasyExcel.read(path, ResData.class, ReadResListener.createListener(new ReadResListener.OnAllAnalysedListener() {
            @Override
            public void onAllAnalysed(boolean isCompleted) {
                for (ResData item : Constants.EXCEL_DATA) {
                    updateValueInProjectXmlFile(item, isNeedMatchModuleName);
                }

                Log.info("total-size", "共有" + Constants.EXCEL_DATA.size() + "---------------------------------------------------------------------------------------------");
                Log.info("error-size", "共有" + ERROR_LOG_LIST.size() + "---------------------------------------------------------------------------------------------");
                //打印出 异常项
                if (!ERROR_LOG_LIST.isEmpty()) {
                    for (String error : ERROR_LOG_LIST) {
                        Log.info("error", error);
                    }
                }
            }
        })).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        Log.info("read", readSheet.getSheetName());
        excelReader.read(readSheet);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();
    }


    /**
     * 更新工程中对应的资源的值
     *
     * @param resData
     */
    private void updateValueInProjectXmlFile(ResData resData, boolean isNeedMatchModuleName) {
        //1）获取到moduel中对应的所有values路径 如 app/src/main/res/values,app/src/main/res/values-en
        HashMap<String, String> targetMap = PathParseProcessor.analysisPath(resData.getPathInfo());

        if (targetMap.isEmpty() || !targetMap.containsKey(Constants.MapKey.MODULE_NAME))
            return;

        //2)根据key进行遍历,注意这里需要先遍历（values下，因为这个values下是一定存在对应的StringKey，其他2个 values-en,values-zh-rTW不保证）
        HashMap<String, List<String>> containModuleMap = PathParseProcessor.getModuleList(targetMap.get(Constants.MapKey.MODULE_NAME), isNeedMatchModuleName);

        //3)只关注values/ ,values-en/ ,values-zh-rTW/ 3个目录
        try {
            //4)注意这里一定是先遍历 values/目录，这行一定要在遍历的最前面
            new CnUpdateModel(resData, targetMap, containModuleMap.get("values")).executeUpdateValues(isNeedMatchModuleName);

            if (!StringUtils.isEmpty(resData.getEnValue())) {
                new EnUpdateModel(resData, targetMap, containModuleMap.get("values-en")).executeUpdateValues(isNeedMatchModuleName);
            }

            new ZhrTWUpdateModel(resData, targetMap, containModuleMap.get("values-zh-rTW")).executeUpdateValues(isNeedMatchModuleName);
            new ThrTHUpdateModel(resData, targetMap, containModuleMap.get("values-th-rTH")).executeUpdateValues(isNeedMatchModuleName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取数据的监听器
     */
    public static class ReadResListener extends AnalysisEventListener<ResData> {

        public static final String TAG = ReadResListener.class.getSimpleName();

        private ReadResListener.OnAllAnalysedListener onAllAnalysedListener;

        public static ReadResListener createListener(ReadResListener.OnAllAnalysedListener onAllAnalysedListener) {
            ReadResListener readResListener = new ReadResListener();
            readResListener.onAllAnalysedListener = onAllAnalysedListener;
            return readResListener;
        }

        @Override
        public void invoke(ResData resData, AnalysisContext analysisContext) {

            if (StringUtils.isEmpty(resData.getPathInfo()))
                return;

            Constants.EXCEL_DATA.add(resData);
            Log.info(TAG, resData.toString());
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            Log.info(TAG, "解析结束--" + Constants.EXCEL_DATA.size());
            if (!Constants.EXCEL_DATA.isEmpty() && null != onAllAnalysedListener) {
                onAllAnalysedListener.onAllAnalysed(true);
            } else {
                onAllAnalysedListener.onAllAnalysed(false);
            }
        }

        /**
         * 全部解析完的，监听接口
         */
        public interface OnAllAnalysedListener {

            /**
             * 解析完成回调方法
             *
             * @param isCompleted
             */
            void onAllAnalysed(boolean isCompleted);
        }
    }
}
